package com.wxcms.ctrl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wxcms.domain.DodemWxCpUser;
import com.wxcms.mapper.EquipmentDao;
import com.wxcms.service.MyWxCpService;
import com.wxcms.service.impl.DodemWxServer;

import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.cp.bean.WxCpUser;

@Controller
@RequestMapping("")
public class IndexController {
	Logger log = Logger.getLogger(this.getClass());
	@Autowired
	private MyWxCpService myWxCpService;
	
   @Autowired
	private EquipmentDao equipdao;
	
	@RequestMapping(value = "/")
	public ModelAndView index(){
		return new ModelAndView("index"); 
	}
	@RequestMapping(value = "error")
	public ModelAndView error(){
		return new ModelAndView("error"); 
	}
	public String getFullUrl(HttpServletRequest request){
		return   "http://" + request.getServerName() //服务器地址  
     
        + request.getContextPath()      //项目名称  
        + request.getServletPath();      //请求页面或其他地址  
	}
	@RequestMapping(value = "/jssdktest/{province}")
	public ModelAndView jssdktest(HttpServletRequest request,@PathVariable String province/*,@PathVariable String token*/){
		ModelAndView  modelAndView= new	 ModelAndView("wxweb/jssdktest");
	 
		DodemWxServer  myService=  myWxCpService.getWxCpServiceByPT(province,"real");
		try {
			//签名用的noncestr和timestamp必须与wx.config中的nonceStr和timestamp相同。
			//签名用的url必须是调用JS接口页面的完整URL
			 log.debug(getFullUrl(request));
			//出于安全考虑，开发者必须在服务器端实现签名的逻辑。
			  WxJsapiSignature apiSign=myService.createJsapiSignature(getFullUrl(request));
			  Object   jsapiOJB= JSONObject.toJSONString(apiSign);
			  modelAndView.addObject("jsapiOJB",jsapiOJB);
			  
			  //与jsapi_ticket类似 企业号管理组权限验证方法
			  WxJsapiSignature groupSign=myService.createSignature(getFullUrl(request));
			  Object   groupOJB= JSONObject.toJSONString(groupSign);
			  modelAndView.addObject("groupOJB",groupOJB);
			  
		} catch (WxErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		myService.getConfig().getJsapiTicket();
		modelAndView.addObject("cfg",JSONObject.toJSONString(myService.getConfig()));

		return modelAndView; 
	}
	
	
	
	@RequestMapping(value = "/sourcelist/{type}/{puid}")
	public ModelAndView imglist(@PathVariable String type,@PathVariable String puid){
		ModelAndView modelAndView = new ModelAndView("mobile/imglist");
		
		modelAndView.addObject("type",type);
		modelAndView.addObject("puid",puid);
		
		
		return modelAndView;  
	}
	/**
	 * 
	 * 这里页面跳转比较慢，需要返回页面在js里面进行跳转，在页面中进行提示
	 * 
	 * 微信  _wxul 必须在微信客户端打开  ， 通过网页跳转不行  只能 在这里跳转
	 * 
	 * */
	@RequestMapping(value = "/mx/{provience}/{token}/{puid}")
	public void  mmindex(HttpServletRequest request,HttpServletResponse response,@PathVariable String province,@PathVariable String token,@PathVariable String puid) throws ServletException{
	//	ModelAndView modelAndView=new ModelAndView("mx"); 
		DodemWxServer  myService=  myWxCpService.getWxCpServiceByPT(province, token);
		
		String _ul=request.getScheme() + "://" + request.getServerName()+"/qyweix/mindex?puid="+puid;
        String _wxul= myService.oauth2buildAuthorizationUrl(_ul,"test");
        
    //	modelAndView.addObject("tardir", _wxul);
        try {
        	
        	response.sendRedirect(_wxul);
        
         
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		return ;
	}
  	
	@RequestMapping(value = "/mindex/{province}")
	public ModelAndView mindex(HttpServletRequest request,@PathVariable String province,@RequestParam(value ="puid" ,required=false, defaultValue="") String puid,
			@RequestParam(value ="type" ,required=false, defaultValue="") String type,@RequestParam(value ="tlong" ,required=false, defaultValue="") String tlong) throws UnsupportedEncodingException{
		ModelAndView modelAndView=new ModelAndView("mindex"); 
		 
		
		String code;
		System.out.println(code = request.getParameter("code"));
		System.out.println(request.getParameter("state"));
		
		request.setAttribute("getcodeOk", true);
		
		// 读取二维码中的时间信息，连同 用户名 写入数据库，标示当前用户通过该二维码 扫码登录了
		String time;
		System.out.println(time = request.getParameter("time"));
		if (code != null) {
			DodemWxServer  myService=  myWxCpService.getWxCpServiceByPT(province,"real");
			DodemWxCpUser user = myWxCpService.getUser(myService,code);
			
			 if(user!=null){
			 
					// 应用的用户
					modelAndView.addObject("uname", user.getName());
					// 应用的用户头像
					modelAndView.addObject("uicon", user.getAvatar());
					//time
					modelAndView.addObject("time", time);
					Integer[] ids=user.getDepartIds();
					 StringBuilder arrayString = new StringBuilder();
					 for (int j = 0, l = ids.length; j < l; j++) {
				            arrayString.append(ids[j]);
				            if (j < l - 1) {
				                arrayString.append(",");
				            }
				        }
				    request.getSession().setAttribute("depidstr", arrayString);
					request.getSession().setAttribute("userid", user.getUserId());
					request.getSession().setAttribute("uname", user.getName());
					request.getSession().setAttribute("icon", user.getAvatar());
					request.getSession().setAttribute("departids", user.getDepartIds());
					
					request.getSession().setAttribute("province", user.getLoginprovince());	
					request.getSession().setAttribute("corpid", user.getCorpid());
					
					String position=user.getPosition();
					if(position==null)
						position="";
					request.getSession().setAttribute("position", position); 
				
					request.getSession().setAttribute("positiond",position.contains("admin")?"true":"false");

				} else
				// 判断用户是否存在，不存在给出添加关注二维码
				{

				}
		}	
		
		
		
		if(!puid.isEmpty()){
			modelAndView.addObject("type",type);
			modelAndView.addObject("puid",puid);
			modelAndView.addObject("tlong",tlong);
			//另外还有一种方法是JavaScript进行一次编码，后台java处理时换种想法就好了：
			 // modelAndView.addObject("name",new String(request.getParameter("name").getBytes("ISO8859-1"), "UTF-8"));
			modelAndView.addObject("name",equipdao.getEquipName(puid));
		}
		return modelAndView; 
	}
}
